Repository navigation
refactor: enhance getBaseModelList to include model_id for credential restoration and add corresponding tests - #8289
Conversation
… restoration and add corresponding tests
| queried_credential = provider.get_model_list.call_args.kwargs["credential"] | ||
| self.assertEqual("sk-live-secret", queried_credential["api_key"]) | ||
| self.assertEqual("sk-live-secret", provider.get_model_list.call_args.kwargs["api_key"]) | ||
| self.assertEqual("sk-live-secret", cache_model_list.call_args.args[2]) |
There was a problem hiding this comment.
Code Review: Provide.ModelList Test Patch
🔴 Critical Issues
1. Test will fail — hard-coded expected value mismatch
self.assertEqual("sk-live-secret", queried_credential["api_key"])The saved credential contains "api_key": "[API_KEY]" (masked), and the test never injects "sk-live-secret" anywhere. Unless rsa_long_encrypt/the view magic replaces it, this assertion cannot pass. Compare the first test which uses "[API_KEY]" as the expected value consistently.
2. cache_model_list.call_args.args[2] is brittle
Index-based access into positional args breaks silently if the signature changes. Use:
cache_model_list.assert_called_once()
args, kwargs = cache_model_list.call_args
self.assertEqual("sk-live-secret", kwargs.get("api_key") or args[2])Better yet, assert on explicit named params.
3. .side_effect = lambda credential: {...} ignores its input
provider.get_model_credential.return_value.encryption_dict.side_effect = lambda credential: {
**credential, "api_key": "[API_KEY]"
}If the view calls this to decrypt/mask, returning a fixed mask means the test never verifies the real save/resolve path. This setup effectively fabricates the outcome you then assert. Consider using the real utility or asserting the mock was called with the decrypted credential.
🟠 Potential Issues
4. Mixing SimpleTestCase → TestCase
Adding TestCase for DB access is correct, but check transactional side effects: if rsa_long_encrypt / Model.objects.create touches other tables or relies on migrations, ensure the test app is in INSTALLED_APPS and migrations are applied for the test DB.
5. Missing assign_role / workspace permissions fixture
The new test creates a Model with workspace_id="workspace-id" but sets no user/permission context. If the view enforces workspace membership, this test may pass only because Provide.ModelList() bypasses auth. Add a comment documenting that assumption, or wire auth consistently with the other tests.
6. request.data mutated after construction
request.data["api_key"] = request.data["credential"]["api_key"]Duplicating top-level api_key from credential mirrors production behavior, but mutating a dict inside SimpleNamespace inline is easy to miss. Build the dict in one literal:
payload = {...}
payload["api_key"] = payload["credential"]["api_key"]
request = SimpleNamespace(data=payload)7. model_id vs provider consistency not validated
The test supplies model_id and a full credential. Make explicit which source wins (saved DB row vs. request body). If the feature is "use saved credential when edit values are masked," assert that the request's masked fields were actually replaced — currently only the final result is checked, not that the DB value was read.
🟡 Optimizations / Style
8. Unused import risk
You added import json, TestCase, rsa_long_encrypt, Model. Verify all are used; otherwise linters (flake8/ruff) will flag them. json and the others do appear used here — good.
9. Large multi-context with block
Python 3.10+ parenthesized with is fine, but patch targets are only scoped over the .post() call. Any downstream lazy import of ModelProvideConstants outside that scope won't be patched. Prefer @patch(...) decorators at method level for clarity and to ensure coverage of the whole call chain.
10. Assert call count on get_model_credential
Add:
provider.get_model_credential.assert_called_once()
provider.get_model_credential.return_value.to_form_list.assert_called_once()to detect redundant lookups or regressions.
11. [API_KEY] masking string should be a constant
Replace literals with a shared constant (e.g., MASKED_API_KEY = "[API_KEY]") to avoid typos across both tests.
12. First test change — verify intentional
- api_key=[API_KEY],
+ api_key="[API_KEY]",Changing from a list ([API_KEY]) to a string is a behavioral change. Confirm the provider now expects a scalar. If [API_KEY] was a variable (not a list), note the diff is misleading — consider renaming the constant so the diff is unambiguous.
✅ Suggested Fix Skelton
MASKED = "[API_KEY]"
REAL_KEY = "sk-live-secret"
def setUp(self):
self.model = Model.objects.create(
...,
credential=rsa_long_encrypt(json.dumps({
"api_base": "...",
"api_key": REAL_KEY, # store real, not masked
})),
)
def test_...(self):
payload = {...} # masked values in request
...
self.assertEqual(REAL_KEY, queried_credential["api_key"])Bottom line: the second assertion set ("sk-live-secret") contradicts the fixture data and will fail; the encryption_dict stub masks the logic under test; and index-based call_args access is fragile. Fix these three before merging.
|
|
||
| assert.equal(requestPayload.model_id, 'model-id') | ||
| assert.deepEqual(requestPayload.credential, credential) | ||
| }) |
There was a problem hiding this comment.
I can only see the test helper, not model-provider.ts, so a few points depend on that file’s import/export style. Main observations:
Potential functional issues
-
The mocked
require('./core/request')shape may not match the transpiled import.- The mock returns the request object directly:
(id) => { ... return request }
- That works only if the source uses a namespace/CommonJS-style import.
- If
model-provider.tsusesimport request from './core/request', TypeScript withmodule: CommonJSand noesModuleInteropwill emitrequest_1.default, so the mock should return{ default: request }(or you should enableesModuleInterop). - If it uses a named import such as
import { request } from './core/request', the mock should return{ request }. - This is the most likely cause of a confusing test failure.
- The mock returns the request object directly:
-
requestPayloadmay beundefined.assert.equal(requestPayload.model_id, 'model-id')
If
postis never called, this throwsTypeErrorinstead of giving a clear assertion failure. Add:assert.ok(requestPayload, 'expected request.post to be called')
-
credentialcan produce a false-positive deep-equal assertion.const credential = { api_key: '[API_KEY]' } ... assert.deepEqual(requestPayload.credential, credential)
Since both references point to the same object, if the code mutates
credential, the assertion still passes. Use a separate expected object or freeze the credential:const credential = Object.freeze({ api_key: '[API_KEY]' }) ... assert.deepEqual(requestPayload.credential, { api_key: '[API_KEY]' })
-
The test does not verify the request path or call count.
It captures only the payload. A wrongpostURL would still pass. Consider capturing both:let requestPath let requestPayload post: (path, payload) => { requestPath = path requestPayload = payload return Promise.resolve([]) }
Then assert
requestPathand thatpostwas called once. -
The custom
requireonly supports./core/request.
Any other runtime import, including Node built-ins, will fail. That is acceptable for a very isolated test, but it is brittle. If the source grows, the mock must be updated. -
compileFunctionlacksmodule,__dirname,__filename, and a filename option.
If the transpiled source referencesmodule.exports,__dirname, etc., the test will fail. At minimum, add a filename for better stack traces:compileFunction(outputText, ['require', 'exports'], { filename: 'model-provider.ts', })
-
Transpile diagnostics are ignored.
ts.transpileModulecan return diagnostics. You may want to assert none exist, or the test can fail later with a less clear error.
Optimization / robustness suggestions
- Cache the transpiled module if more tests are added; do not read and transpile the source repeatedly.
- Ensure the relative path
../src/api/admin/model-provider.tsis correct for the actual test file location. - Prefer the project’s existing TypeScript test runner/build setup over runtime
transpileModule+vm.compileFunctionif available; this custom loader is fragile. - Consider asserting that
getBaseModelListdoes not mutate the passed credential, especially if credentials are sensitive. - The Chinese test name is not a problem, but using English may improve consistency if the rest of the suite is English.
Overall: no security issue in this test code, but the module mock shape and same-reference credential assertion are the main correctness risks.
|
|
||
| def get_cached_base_model_list(provider, model_type, model_id=None, credential=None): | ||
| """按 url+key 读取缓存的官方模型列表,未命中返回空列表。 | ||
|
|
There was a problem hiding this comment.
Here are the issues and suggestions:
Correctness / Logic
-
Wrong-merging direction of trust. The loop compares
restored[key] == encrypted_value(the re-encrypted real value). But the form's untouched masked field likely holds the masked/display value sent to the frontend, not the encrypted value. That means the comparison will rarely match, so restoration silently does nothing. You should compare against the actual value the form would have received — i.e., whateverget_model_credential(...).encryption_dict(...)outputs for display, or against a mask constant. Verify which representation the UI echoes back. -
Overwriting with
None.source_credential.get(key)returnsNoneif the key is missing from the stored credential. Since you only enter this branch when the keys matched, an absent key would replace a previously valid value withNone. Guard withif key in source_credential. -
Broad
except Exception: return credentialswallows decryption errors, badproviderlookups (ModelProvideConstants[provider]raisesKeyError), and programming bugs alike. Narrow the exceptions (e.g.JSONDecodeError, decryption errors,KeyError) and log them; otherwise you'll never diagnose silent failures in production. -
provider_handler or ModelProvideConstants[provider]— ifprovider_handleris passed but incomplete/mismatched, no validation. AlsoModelProvideConstants[provider]is evaluated lazily (good), but ensureprovideris always a valid constant here. -
Security: restoring credentials for any
model_id. There's no check that the caller is allowed to edit/view that model's credential. Filtering byprovider/model_typehelps but doesn't tie the lookup to the requesting user/tenant. If this runs on user-supplied input, it can be used to exfiltrate other models' secrets (IDOR). Add an ownership/permission check.
Optimization / Style
-
Query efficiency.
Model(id, provider, model_type).first()is fine, but ensure there's an index covering(id, provider, model_type)—the PK alone is enough since it's unique; the extra filters just add safety. Consider.only("credential", "model_name")to avoid loading all columns. -
Unnecessary copy.
restored = dict(credential)then mutate — fine, but if nothing is restored you return a copy rather than the original. Minor; consider tracking whether any restoration happened and returningcredentialuntouched otherwise (avoids surprising identity changes for callers). -
Repeated re-encryption cost. Calling
encryption_dicton every edit request re-does RSA/encryption work merely to compare strings. If possible, compare against a cheaper canonical form (e.g., a hash) or a stored "is-masked" flag/sentinel instead. -
Docstring/comment is Chinese while the rest of the codebase may be English — consistency nit. Also the return type/contract (may return the same object, a copy, or original) should be documented.
-
Naming.
encrypted_valueis misleading — it's the re-encrypted version of the stored secret, being compared to a possibly-masked form input. Rename toexpected_masked/real_encryptedto clarify intent. -
Testability. No unit-test-friendly seam for decryption/handler; consider injecting these or at least testing the no-match, missing-key, and decrypt-failure paths.
Highest priority: #1 and #2 (the function likely doesn't do what the docstring claims, and can null out secrets), then #5 (security) and #3 (silent failures).
refactor: enhance getBaseModelList to include model_id for credential restoration and add corresponding tests